import { FastifyPluginAsync } from "fastify";
import { RoomItemDocument, SearchParams } from "./type";
import { Collection } from "mongodb";

function buildQuery(params: SearchParams): Record<string, any> {
  const query: Record<string, any> = { isDeleted: { $ne: true } };

  const fields: (keyof SearchParams)[] = ["invitedParentRoom"];

  fields.forEach((field) => {
    if (params[field]) {
      query[field] = params[field];
    }
  });

  if (params.messages) {
    query.messages = { $regex: new RegExp(params.messages, "i") };
  }

  return query;
}

const getInvitedRoomsRoutes: FastifyPluginAsync = async (fastify, opts) => {
  const db = fastify.mongo.db;

  const getCollection = (): Collection<RoomItemDocument> => {
    if (!db) {
      console.error("MongoDB not connected");
    }
    // @ts-ignore
    return db.collection<RoomItemDocument>("invitedRooms");
  };

  fastify.get(
    "/get-invitations-by-room1",
    {
      schema: {
        querystring: {
          type: "object",
          properties: {
            page: { type: "string", pattern: "^\\d+$", default: "1" },
            pageSize: { type: "string", pattern: "^\\d+$", default: "10" },
            // 其他查询参数...
          },
        },
      },
    },
    async function (request, reply) {
      const {
        page = "1",
        pageSize = "10",
        ...searchParams
      } = request.query as SearchParams;

      const pageNum = Math.max(1, parseInt(page, 10)) || 1;
      const limitNum = Math.min(Math.max(1, parseInt(pageSize, 10) || 10), 100);
      const skip = (pageNum - 1) * limitNum;

      const collection = getCollection();
      const query = buildQuery(searchParams);

      const [total, rooms] = await Promise.all([
        collection.countDocuments(query),
        collection
          .find(query)
          .sort({ createdAt: -1 })
          .skip(skip)
          .limit(limitNum)
          .toArray(),
      ]);

      return {
        success: true,
        data: {
          list: rooms,
          pagination: {
            total,
            page: pageNum,
            pageSize: limitNum,
            totalPages: Math.ceil(total / limitNum),
          },
        },
      };
    },
  );
};

export default getInvitedRoomsRoutes;
